import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
from langchain_ollama import OllamaEmbeddings
from langchain.chains import RetrievalQA
try:
    # 定义文本列表
    texts = [
        "Hi there!",
        "Oh, hello!",
        "What's your name?",
        "My friends call me World",
        "Hello World!"
    ]

    # 使用Ollama的嵌入模型
    embeddings_model = OllamaEmbeddings(
        base_url='http://192.168.2.208:11434',
        model="nomic-embed-text")

    embeddings = embeddings_model.embed_documents(texts)

    print(f"处理了 {len(texts)} 个文本")
    print(f"每个文本的嵌入维度: {len(embeddings[0])}")

    # 建立文本和向量的对应关系
    print("\n=== 文本与向量对应关系 ===")
    for i, (text, vector) in enumerate(zip(texts, embeddings)):
        print(f"\n文本 {i+1}: '{text}'")
        print(f"向量前5维: {vector[:5]}")
        print(f"向量长度: {len(vector)} 维")

    # 计算相似度示例
    print("\n=== 相似度分析 ===")

    # 计算第一个文本与其他文本的相似度
    base_vector = np.array(embeddings[0]).reshape(1, -1)
    for i, (text, vector) in enumerate(zip(texts[1:], embeddings[1:]), 1):
        compare_vector = np.array(vector).reshape(1, -1)
        similarity = cosine_similarity(base_vector, compare_vector)[0][0]
        print(f"文本1与文本{i+1}的相似度: {similarity:.4f}")

except Exception as e:
    error_msg = f"执行错误: {e}"
    print(error_msg)